<?php
class attachment extends Admin {

    // 文件上传
    public function upload() {
        // cookie 验证失败
        if ( md6( R( 'cookie_auth' ), 'decode' ) != APP_COOKIE ) {
            exit( json_encode( array( 'file' => 'error' ) ) );
        }

        $name = 'Filedata';
        $updir = $this->setting[ 'updir' ];
        $rename = R( 'rename', true );

        // 上传出错
        if ( $_FILES[ $name ][ "error" ] > 0 ) {
            exit( json_encode( array( 'file' => 'error' ) ) );
        }

        $tempFile = $_FILES[ $name ][ 'tmp_name' ];

        // 创建上传目录
        $dir = rtrim( date( $updir ), '/' ) . '/';
        $filePath = "/content/attachment/" . $dir;
        mkdirs( APP_PATH . $filePath );

        // 上传文件名
        $fileName = $_FILES[ $name ][ 'name' ];

        // 重命名文件
        if ( $rename ) {
            $fileParts = pathinfo( $fileName );
            $fileExt = strtolower( $fileParts[ 'extension' ] ) == 'bmp' ? 'jpg' : strtolower( $fileParts[ 'extension' ] );
            $fileName = strtolower( substr( md5( uniqid() . time() ), 8, 16 ) . '.' . $fileExt );
        }

        // 文件绝对路径
        $filePath .= $fileName;
        $file = APP_PATH . $filePath;

        // 保存文件到本地
        if ( !move_uploaded_file( $tempFile, $file ) ) {
            exit( json_encode( array( 'file' => 'error' ) ) );
        }

        $img = @getimagesize( $file ) ? 1 : 0;
        $id = $this->save( $filePath, $img );
        exit( json_encode( array( 'file' => $filePath, 'id' => $id, 'img' => $img ) ) );
    }

    /*
     * 写入附件到到数据库并返回附件ID
     *
     * @param $file      附件路径
     * @param $isImg     是否为图片
     */
    private function save( $file, $isImg ) {
        $this->model->table = "attachment";
        $rows[ 'filename' ] = basename( $file );
        $rows[ 'filepath' ] = $file;
        $rows[ 'filesize' ] = formatFileSize( filesize( APP_PATH . $file ) );
        $rows[ 'dateline' ] = time();
        $rows[ 'isImage' ] = $isImg;
        return $this->model->create( $rows );
    }

    // 删除附件
    public function del() {
        if ( !$id = intval( R( "id" ) ) ) {
            $this->error();
        }

        $this->model->table = "attachment";
        if ( !$result = $this->model->find( array( "id" => $id ) ) ) {
            $this->error( "附件id:{$id}不存在" );
        }
        // 删除附件
        $this->model->delete( array( "id" => $id ) );

        // 删除文章附件计数
        $this->model->table = "article";
        $this->model->decrField( array( 'id' => $result[ 'aid' ] ), 'attachments' );

        // 删除文件
        @unlink( APP_PATH . $result[ 'filepath' ] );

        $this->success( "删除附件ID：{$id}成功" );
    }
}